import poService from "@/api/services/wms/poService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import SingleMaterialSelector from "@/pages/components/selector/SingleMaterialSelect";
import { ExportOutlined } from "@ant-design/icons";
import { Button, DatePicker, Input, InputNumber, Space } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from "react";
import { toast } from "sonner";
import type { ScmPurchaseDetail } from "./entity";
import dayjs from 'dayjs';


interface ScmPurchaseDetailProps {
	parentId: React.Key;
}

export interface ScmPurchaseDetailHandles {
	getAddList: () => ScmPurchaseDetail[];
  getUpdateList: () => ScmPurchaseDetail[];
	getDeleteIds: () => React.Key[];
}

const ScmPurchaseDetailPage = forwardRef<ScmPurchaseDetailHandles, ScmPurchaseDetailProps>(({ parentId }, ref) => {
	const [loading, setLoading] = useState(false);
	const [list, setList] = useState<ScmPurchaseDetail[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [editedRowKey, setEditedRowKey] = useState<React.Key>();
  // 添加一个状态来跟踪临时ID
  const [tempIds, setTempIds] = useState<React.Key[]>([]);
  const [addList, setAddList] = useState<ScmPurchaseDetail[]>([]);
  const [updateList, setUpdateList] = useState<ScmPurchaseDetail[]>([]);
	const [deleteIds, setDeleteIds] = useState<React.Key[]>([]);
	const [selectVisiable, setSelectVisiable] = useState(false);

	useImperativeHandle(
		ref,
		() => ({
			getAddList: () => addList,
      getUpdateList: () => updateList,
			getDeleteIds: () => deleteIds,
		}),
		[addList, updateList, deleteIds],
	);

  useEffect(() => {
    const newAddList = list.filter((item) => item.id && tempIds.includes(item.id));
    setAddList(newAddList);
    const updateList = list.filter((item) => item.id && !tempIds.includes(item.id));
    setUpdateList(updateList);
  }, [list]);

	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 403;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	const columns: ColumnsType<ScmPurchaseDetail> = [
		{
			title: "物料编码",
			width: 150,
			key: "materialCode",
			dataIndex: "materialCode",
			render: (text, record) => (
				<Space.Compact block>
					<Input style={{ width: "calc(100% - 32px)" }} value={text} disabled />
					<Button icon={<ExportOutlined />} onClick={() => openSelectMaterial(record.id)} />
				</Space.Compact>
			),
		},
		{
			title: "物料名称",
			width: 200,
			key: "materialName",
			dataIndex: "materialName",
		},
		{
			title: "采购数量",
			width: 120,
			key: "qty",
			dataIndex: "qty",
			render: (text, record) => (
				<InputNumber value={text} onChange={(value) => handleFieldChange(record.id, "qty", value)} />
			),
		},
		{
			title: "交货日期",
			width: 200,
			key: "deliveryDate",
			dataIndex: "deliveryDate",
			render: (text, record) => (
				<DatePicker 
					value={text ? dayjs(text) : null} 
					format="YYYY-MM-DD" 
					onChange={(date) => handleFieldChange(record.id, "deliveryDate", date)} 
				/>
			),
		},
		{
			title: "备注",
			width: 200,
			key: "remark",
			dataIndex: "remark",
			render: (text, record) => (
				<Input value={text} onChange={(e) => handleFieldChange(record.id, "remark", e.target.value)} />
			),
		},
		{
			title: "最近交货日期",
			width: 200,
			key: "latestDeliveryDate",
			dataIndex: "latestDeliveryDate",
		},
		{
			title: "总收货量",
			width: 120,
			key: "totalReceivedQty",
			dataIndex: "totalReceivedQty",
		},
	];

	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => (col.key ? String(col.key) : "")),
	);

	// 处理字段变更
	const handleFieldChange = (id: string, field: string, value: any) => {
		// 如果是checkbox的值，将布尔值转换为数字值（true为1，false为0）
		const processedValue = typeof value === "boolean" ? (value ? 1 : 0) : value;
		
		// 处理日期格式
		if (field === "deliveryDate" && value) {
			// 将日期转换为指定格式的字符串
			const formattedDate = dayjs(value).format('YYYY-MM-DD');
			setList((prevData) => prevData.map((item) => (item.id === id ? { ...item, [field]: formattedDate } : item)));
			return;
		}
		
		setList((prevData) => prevData.map((item) => (item.id === id ? { ...item, [field]: processedValue } : item)));
	};

	const filteredColumns = useMemo(() => {
		return [...columns.filter((col) => selectedValues.includes(String(col.key)) || col.key === "operation")].sort(
			(a, b) => {
				const originalIndex = columns.findIndex((c) => c.key === a.key);
				const targetIndex = columns.findIndex((c) => c.key === b.key);
				return originalIndex - targetIndex;
			},
		);
	}, [selectedValues]);

	//加载表格数据
	const fetchList = () => {
		if (!parentId) return;

		setLoading(true);
		poService
			.getDetails(parentId).then((res) => {
				setList(res);
			}).catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		fetchList();
	}, [parentId]);

	//检验是否输入值
	const validatePartsBeforeAdd = (): boolean => {
		for (const detail of list) {
			if (!detail.materialId) {
				toast.error("物料不能为空");
				return false;
			}
			if (!detail.qty) {
				toast.error("采购数量不能为空");
				return false;
			}
			if (!detail.deliveryDate) {
				toast.error("交货日期不能为空");
				return false;
			}
		}
		return true;
	};

	const handleAdd = () => {
	    if (!validatePartsBeforeAdd()) {
	        return; // 校验未通过，不执行新增
	    }
	
	    const newId = Date.now().toString();
	    const newDetail: ScmPurchaseDetail = {
	        id: newId,
	        purchaseId: parentId,
	    };
	
	    // 添加到临时ID列表
	    setTempIds(prev => [...prev, newId]);
	    setList((prevParts) => [...prevParts, newDetail]);
	};
	
  const openSelectMaterial = (id : React.Key) => {
    setSelectVisiable(true);
    setEditedRowKey(id);
  }
	// 在删除方法中修改判断逻辑
	const handleDelete = async () => {
	    // 如果没有选中行，直接返回
	    if (selectedRowKeys.length === 0) {
	        return;
	    }
	    
	    // 更新删除ID列表
	    const newDeleteIds = [...deleteIds];
	    
	    // 将已有ID但不在deleteIds中的ID添加到deleteIds
	    for (const key of selectedRowKeys) {
	        const item = list.find(item => item.id === key);
        if (item?.id && !tempIds.includes(item.id)) {
	            // 如果不在临时ID列表中，则添加到删除列表
	            if (!newDeleteIds.includes(item.id)) {
	                newDeleteIds.push(item.id);
	            }
	        }
	    };
	    
	    // 更新deleteIds状态
	    setDeleteIds(newDeleteIds);
	    
	    // 从列表中移除选中的行
	    setList(prevList => prevList.filter(item => !selectedRowKeys.includes(item.id)));
	    // 从tempIds中移除被删除的临时ID
      setTempIds(prevTempIds => prevTempIds.filter(id => !selectedRowKeys.includes(id)));
	    // 清空选中状态
	    setSelectedRowKeys([]);
	};

  const handleSelectMaterial = (item: any) => {
    setSelectVisiable(false);
    if (item) {
      const { id,materialCode, materialName } = item;

      setList((prevData) => prevData.map((item) => (item.id === editedRowKey ? 
        { ...item, materialId:id, materialCode:materialCode, materialName:materialName } : item)));
    }
  }

	return (
		<>
			<div className="flex justify-between mb-4">
				<div className="flex gap-2">
					<Button type="primary" onClick={handleAdd}>
						新增
					</Button>
					<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
						删除
					</Button>
				</div>
				<TableToolbar
					onRefresh={() => fetchList()}
					onSizeChange={setTableSize}
					columns={columns}
					selectedValues={selectedValues}
					onColumnChange={setSelectedValues}
				/>
			</div>
			<Table
				rowKey="id"
				size={tableSize}
				scroll={{ x: "max-content", y: tableScrollY }}
				loading={loading}
				pagination={false}
				columns={filteredColumns}
				dataSource={list}
				rowSelection={{
					type: "checkbox",
					selectedRowKeys: selectedRowKeys,
					onChange: (selectedKeys) => {
						setSelectedRowKeys(selectedKeys as React.Key[]);
					},
				}}
			/>

			{/* 物料选择器 */}
			<SingleMaterialSelector
				open={selectVisiable}
				onCancel={() => setSelectVisiable(false)}
				onOk={(item) => handleSelectMaterial(item)}
			/>
		</>
	);
});

export default ScmPurchaseDetailPage;
